// pages/home/subscribe/list/com/subscribeList/subscribeList.js
const app = getApp();
import api from "./../../../../../../common/api"
import * as filterConfig from './../../../../../../models/filter'
import * as user from '../../../../../../models/user'

const DEFAULT_TIME = '7'

Component({
  /**
   * 组件的配置
   */
  options: {
    styleIsolation: 'isolated',
    pureDataPattern: /^_/
  },
  /**
   * 组件的属性列表
   */
  properties: {
    range: {
      type: String,
      value: '',
    },
    type: {
      type: String,
      value: '',
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    _isRefreshVipStatus: false,
    subscribeTotal: 0,
    dynamicTotal: 0,
    vipStatus: '',
    isShowOverview: true,
    total: 0,
    isShowCity: false,
    pageIndex: 0,
    pageSize: 20,
    houseList: [],
    hasMoreList: true,
    isShowDue: false,
    missHouseNum: 0,
    search: {},
    cityName: '全国',
    cityCode: 'all',
    citys: [],
    infoTypeCurrent: [],
    infoTypeOptions: [{
      value: '0',
      label: '新上'
    }, {
      value: '1',
      label: '带看'
    }, {
      value: '2',
      label: '调价'
    }, {
      value: '3',
      label: '下架'
    }],
    filterMore: {
      time: DEFAULT_TIME
    },
    filterOptions: [{
      id: 'time',
      title: '时间',
      single: filterConfig.rangeAddTime,
      defaultValue: DEFAULT_TIME
    }, {
      id: 'type',
      title: '类型',
      single: filterConfig.rangeSalesType
    }],
  },

  /**
   * 组件的数据监听
   */
  observers: {

  },

  /**
   * 组件的生命周期
   */
  lifetimes: {
    attached: function () {
      app.globalData.loginPromise.then(() => {
        this.initData()
        this.getResblockByDay()
          .then(() => {
            this.loadMissHouseNum()
            this.checkUserAuth()
          })
        this.loadHouse()
          .then(() => {
            this.getExistCity()
          })
      })
    },
    detached: function () {},
  },

  /**
   * 页面的生命周期
   */
  pageLifetimes: {
    show: function () {
      this.refreshMySubscribe()
      this.refreshVip()
    },
    hide: function () {
      // 页面被隐藏
    },
    resize: function (size) {
      // 页面尺寸变化
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {

    initData() {
      const {
        range,
        type,
        filterMore
      } = this.data
      if (range) {
        this.setData({
          filterMore: Object.assign(filterMore, {
            type: range
          })
        })
      }
      if (type) {
        this.setData({
          infoTypeCurrent: type.split(',') || []
        })
      }
    },

    onPageScroll(e) {
      const {
        isShowOverview
      } = this.data
      if (e.scrollTop > 2 && isShowOverview) {
        this.setData({
          isShowOverview: false,
        })
      }
      if (e.scrollTop < 2 && !isShowOverview) {
        this.setData({
          isShowOverview: true,
        })
      }
    },

    onPageReachBottom() {
      this.loadHouse()
    },

    getExistCity() {
      return new Promise((resolve, reject) => {
        api.getExistCity({}, (res) => {
          let result = [{
            value: "all",
            label: "全国"
          }]
          if (res && res.data && res.data.content && res.data.content.length) {
            try {
              let formatResult = res.data.content.map(item => {
                return {
                  value: item.cityCode,
                  label: item.cityName
                }
              })
              result = [...result, ...formatResult]
            } catch (error) {
              
            }
          }
          this.setData({
            citys: result
          })
        })
      })
    },

    onSwitchCity() {
      this.setData({
        isShowCity: true
      })
    },

    onSwitchCityClose() {
      this.setData({
        isShowCity: false
      })
    },

    onCityChange(e) {
      const {
        form = {}
      } = e.detail
      const {
        citys
      } = this.data
      citys.forEach(item => {
        if (item.value === form.city) {
          this.setData({
            cityCode: item.value,
            cityName: item.label,
          })
          this.resetHouseData()
          this.loadHouse()
        }
      })
    },

    // 用户权限校验
    checkUserAuth() {
      let {
        subscribeTotal
      } = this.data
      user.updateVip()
        .then(res => {
          if (res !== '0' && subscribeTotal) {
            this.setData({
              vipStatus: res,
              isShowDue: true
            })
          }
        })
    },

    // 开通vip
    onOpenVip() {
      this.data._isRefreshVipStatus = true
      wx.navigateTo({
        url: '/pages/mine/memberCentre/memberCentre?orderEntr=新上房源列表',
      })
    },

    // 检察vip更新
    refreshVip() {
      if (this.data._isRefreshVipStatus) {
        this.data._isRefreshVipStatus = false
        user.getVip()
          .then(res => {
            if (res === '0') {
              this.setData({
                isShowDue: false
              })
            }
          })
      }
    },

    // 订阅错过房源数量
    loadMissHouseNum() {
      return new Promise((resolve, reject) => {
        api.skipExternalHouse({}, (res) => {
          if (res && res.data && res.data.isSuccess) {
            this.setData({
              missHouseNum: res.data.content || 0,
            })
            resolve()
          } else {
            resolve()
          }
        })
      })
    },

    // 搜索
    onSearchChange(e) {
      this.setData({
        search: e.detail,
      })
      this.resetHouseData()
      this.loadHouse()
    },

    onFilterChange(e) {
      this.setData({
        filterMore: e.detail.form,
      })
      this.resetHouseData()
      this.loadHouse()
    },

    onInfoTypeChange(e) {
      this.setData({
        infoTypeCurrent: e.detail
      })
      this.resetHouseData()
      this.loadHouse()
    },

    loadHouse() {
      let t = this
      return new Promise((resolve, reject) => {
        let {
          pageIndex,
          pageSize,
          cityCode,
          hasMoreList,
          search,
          filterMore,
          infoTypeCurrent
        } = t.data
        if (!hasMoreList) {
          resolve()
          return
        }
        wx.showLoading({
          title: '加载中...',
        })
        let currentIndex = pageIndex + 1
        api.getSubscribeList({
          scopeState: filterMore.type ? Number(filterMore.type) : null,
          intelligenceType: infoTypeCurrent && infoTypeCurrent.length ? infoTypeCurrent.join() : null,
          newExternalTime: Number(filterMore.time),
          pageSize: pageSize,
          pageNum: currentIndex,
          cityCode: cityCode === 'all' ? '' : cityCode,
          hdResblockId: search.type === 'id' ? search.value : '',
        }, (res) => {
          wx.hideLoading()
          if (res && res.data && res.data.isSuccess && res.data.content) {
            let result = res.data.content.pageInfo || {}
            let list = result.list || []
            let maxIndex = result.pages
            let formatList = list.map(item => {
              return {
                houseDistrict: item.area || '',
                houseDistrictId: item.areaCode || '',
                houseCityName: item.city || '',
                houseCityCode: item.cityCode || '',
                houseCommunityID: item.hdResblockId || '',
                houseCommunityName: item.resblockName || '',
                houseDddress: item.addr || '',
                houseBizcircleId: item.bizcircleId || '',
                houseBizcircleName: item.bizcircleName || '',
                isSoldOutNum: item.isSoldOutNum || 0,
                monthLookNum: item.monthLookNum || 0,
                newPushNum: item.newPushNum || 0,
                priceNum: item.priceNum || 0,
              }
            })
            if (currentIndex === 1) {
              t.setData({
                total: res.data.content.count
              })
              t.data.houseList = [...formatList]
            } else {
              t.data.houseList.push(...formatList)
            }
            t.setData({
              pageIndex: currentIndex,
              hasMoreList: currentIndex >= maxIndex ? false : true,
              houseList: t.data.houseList
            })
            resolve()
          } else {
            reject()
          }
        }, () => {
          wx.hideLoading()
          reject()
        });
      })
    },

    // 重置列表数据
    resetHouseData() {
      this.setData({
        houseList: [],
        pageIndex: 0,
        hasMoreList: true,
      })
      wx.pageScrollTo({
        scrollTop: 0,
        duration: 0
      })
    },

    // 取消订阅
    onCancelSubscribe(e) {
      api.subscribe({
        hdResblockId: e.detail,
        stated: 1
      }, res => {
        if (res && res.data && res.data.isSuccess) {
          this.resetHouseData()
          this.getResblockByDay()
          this.getExistCity()
          this.loadHouse()
        } else {
          wx.showToast({
            icon: 'none',
            title: '取消订阅失败,请稍后再试~',
          })
        }
      })
    },

    // 检察订阅列表更新
    refreshMySubscribe() {
      const lastSubscribeTotal = this.data.subscribeTotal || 0
      this.getResblockByDay()
        .then(() => {
          if (lastSubscribeTotal !== this.data.subscribeTotal) {
            this.resetHouseData()
            this.getExistCity()
            this.loadHouse()
          }
        })
    },

    // 点击小区
    onClickHouse(e) {
      const {
        filterMore,
        infoTypeCurrent,
      } = this.data
      const {
        houseCommunityID,
        houseCommunityName,
        houseCityCode,
      } = e.detail || {}
      let tab = ['', 'sales', 'rent'][filterMore.type] || '';
      let type = infoTypeCurrent && infoTypeCurrent.length ? infoTypeCurrent.join() : ''
      let time = filterMore.time || ''
      wx.navigateTo({
        url: `/pages/home/subscribe/myList/myList?id=${houseCommunityID}&name=${houseCommunityName}&citycode=${houseCityCode}&tab=${tab}&type=${type}&time=${time}`,
      })
    },

    onTouchMove() {
      return false
    },

    onClickEmptyBtn() {
      const page = this.getPage()
      page && page.onClickSubscribe()
    },

    onSubscribeSetting() {
      wx.navigateTo({
        url: '/pages/home/subscribe/setting/setting',
      })
    },

    getPage() {
      return getCurrentPages() ? getCurrentPages()[getCurrentPages().length - 1] : {}
    },

    // 订阅小区概览
    getResblockByDay() {
      return new Promise((resolve, reject) => {
        api.getResblockByDay({}, (res) => {
          if (res && res.data && res.data.content) {
            const {
              resblockCount,
              subscribeResblockCount
            } = res.data.content
            this.setData({
              subscribeTotal: subscribeResblockCount || 0,
              dynamicTotal: resblockCount || 0,
            })
          }
          resolve()
        })
      })
    }
  }


})